/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-04-09 16:53:59
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-04-29 10:10:35
 * @FilePath: \vite-project\src\components\common\CommonImport.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useTokenStore } from 'store/user';
import { Icon } from '@iconify/react/dist/iconify.js';
import { Alert, App, Button, Space, Upload, UploadFile, type UploadProps } from 'antd';
import { nanoid } from 'nanoid';

const CommonImport: React.FC<{
    uploadUrl: string;
    templateUrl: string;
    onSuccess: () => void;
}> = ({ uploadUrl, templateUrl, onSuccess }) => {
    const { message } = App.useApp();
    const { token, currentTenant } = useTokenStore();
    const isExcelFileMimeType = (file: UploadFile) => {
        const excelMimeTypes = [
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ];
        return file.type && excelMimeTypes.includes(file.type);
    };
    const props: UploadProps = {
        name: 'file',
        action: uploadUrl,
        listType: 'text',
        accept: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        headers: {
            authorization: 'authorization-text',
            'recycloud-appId': '1774698536038961152',
            'recycloud-token': token,
            'recycloud-tenant': currentTenant,
        },
        data: (data) => {
            return {
                domain: 'recycloud-web-ui',
                timeStamp: new Date().getTime(),
                transId: nanoid(),
                signMethod: 'MD5',
                apiVersion: 'v1.0',
                data: JSON.stringify({}),
            };
        },
        beforeUpload: (file: UploadFile) => {
            const isExel = isExcelFileMimeType(file);
            if (!isExel) {
                message.error(`只能上传Excel文件类型，请重新上传`);
            }
            return isExel || Upload.LIST_IGNORE;
        },
        onChange: ({ file, fileList }: { file: UploadFile; fileList: UploadFile[] }) => {
            let uploadComplete = true;
            let uploadErrorMsg = '';
            for (let i = 0; i < fileList.length; i++) {
                if (fileList[i].status === 'uploading') {
                    uploadComplete = false;
                    break;
                }
                if (fileList[i]?.response?.rspCode !== '000000') {
                    uploadErrorMsg = fileList[i]?.response?.rspDesc;
                }
                if (fileList[i].status === 'uploading') {
                    uploadComplete = false;
                    break;
                }
            }
            if (uploadErrorMsg) {
                message.error(uploadErrorMsg);
                return;
            }
            if (uploadComplete) {
                message.success('上传成功');
                onSuccess?.();
            }
        },
        maxCount: 1,
        showUploadList: false,
    };

    return (
        <>
            <Alert
                message='请先下载模板文件，下载填写完成后再上传模板文件，模板文件格式为excel'
                type='warning'
                className='mb-12px'
            />
            <Space>
                <Upload {...props}>
                    <Button icon={<Icon icon='ant-design:upload-outlined'></Icon>}>上传</Button>
                </Upload>
                <a href={templateUrl}>下载模板</a>
            </Space>
        </>
    );
};

export default CommonImport;
